package drone.iqgc.common ;

import java.util.Locale ;
import java.util.Objects ;

import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;
import org.springframework.beans.BeansException ;
import org.springframework.context.ApplicationContext ;
import org.springframework.context.ApplicationContextAware ;
import org.springframework.stereotype.Component ;
import org.springframework.web.context.ContextLoader ;

import drone.basis.util.StringUtil ;

@Component
public class ContextAware implements ApplicationContextAware
{

	private static final Logger logger = LoggerFactory.getLogger ( ContextAware.class ) ;

	private static ApplicationContext applicationContext = null ;

	public void setApplicationContext (
			ApplicationContext applicationContext
	) throws BeansException
	{
		for ( String beanName : applicationContext.getBeanDefinitionNames ( ) )
		{
			logger.debug ( "application bean registe : " + beanName ) ;
		}

		ContextAware.applicationContext = applicationContext ;
	}

	public static ApplicationContext getApplicationContext ( )
	{
		return applicationContext ;
	}

	@SuppressWarnings ( "unchecked" )
	public static < T > T getBean (
			String name
	)
	{
		if ( ! Objects.isNull ( ContextLoader.getCurrentWebApplicationContext ( ) ) )
		{
			return ( T ) ContextLoader.getCurrentWebApplicationContext ( ).getBean ( name ) ;
		} else
		{
			return ( T ) applicationContext.getBean ( name ) ;
		}
	}

	public static String getMessage (
			String key
	)
	{
		return applicationContext.getMessage ( key , null , Locale.getDefault ( ) ) ;
	}

	public static String getActiveProfile ( )
	{
		return applicationContext.getEnvironment ( ).getActiveProfiles ( ) [ 0 ] ;
	}

	public static boolean isTest ( )
	{

		if ( StringUtil.isEmpty ( applicationContext.getEnvironment ( ).getActiveProfiles ( ) [ 0 ] ) )
		{
			return true ;
		}

		if ( applicationContext.getEnvironment ( ).getActiveProfiles ( ) [ 0 ].equals ( "develop" ) )
		{
			return true ;
		}

		if ( applicationContext.getEnvironment ( ).getActiveProfiles ( ) [ 0 ].equals ( "production" ) )
		{
			return true ;
		}

		if ( applicationContext.getEnvironment ( ).getActiveProfiles ( ) [ 0 ].endsWith ( "develop" ) )
		{
			return true ;
		}

		return false ;
	}

}
